#!/usr/bin/python

import re
import zutil

# TODO: this code should be rewritten to dynamically generate the code
# using a python list 'tokens' and 'aliases' rather than static text

def inject_text(s_code, s_find, s_file):
    #print s_code
    #print s_find
    
    s_find = s_find.replace("(","\(")
    s_find = s_find.replace(")","\)")

    # add the () to capture the text
    s_find = s_find.lstrip().rstrip()
    s_find = r"(" + s_find + ")"
    #print s_find
    
    s_code = s_code.rstrip()
   
    p = re.compile(s_find)
    result = p.subn(r"\1 " + s_code, s_file)
    result_str = result[0]
    result_num = result[1]

    #print result_num
    #print result_str
    if result_num == 0:
        raise Exception("scanner.cc: No match for text: \n" + s_find)
    if result_num > 1:
        raise Exception("scanner.cc: Too many matches for place to insert zed code")
        
    return result_str

    
def process_file(s_filename, datafile):
    """ to the datafile to inject new zed code at points in the 
        source code files """

    # read data file
    f = open(datafile)
    s_data = f.read() 
    f.close()
    
    # read the file
    f = open(zutil.get_read_path(s_filename))
    s_file = f.read() 
    f.close()
    
    # use the data file to get the text to inject and the inject it!
    data = re.split("=====", s_data)
    for i in data:
        data2 = re.split("#####", i)
        if len(data2) != 2:
            raise Exception(filename + "scanner.cc - screw up in splitting data file" + datafile)
     
        s_code = data2[0]  
        s_find = data2[1]
        s_file = inject_text(s_code, s_find, s_file)

    # write the file
    f = open(zutil.get_write_path(s_filename), "w")
    f.write(s_file)
    f.close()    
    

def update_scannercc():
    process_file("scanner.cc", "zdata_scannercc")


def update_scannerh():
    process_file("scanner.h", "zdata_scannerh")

    
# main
def main():
    update_scannercc()
    update_scannerh()


# call the main function
if __name__ == "__main__":
    main()


